<template>
  <div class="app-container" style="height: 100%; padding-bottom: 0" :class="{ disabled: disableAction }">
    <el-form ref="queryForm" :model="queryParams" size="mini" inline style="white-space: nowrap; overflow-x: auto">
      <el-form-item prop="patTypeName">
        <el-input v-model.trim="queryParams.patTypeName" placeholder="请输入巡更类型名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button size="mini" :icon="isExpand ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" @click="handleExpandDebounce">全部{{ isExpand ? '折叠' : '展开' }}</el-button>
        <el-button size="mini" type="primary" icon="el-icon-plus" @click="$refs.EditItem.open({}, { treeData: list })" v-if="showBtns.add">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table
      class="table g-table-tree-expand-align"
      ref="table"
      v-loading="listLoading"
      :data="filteredList"
      size="small"
      row-key="patTypeId"
      highlight-current-row
      :default-expand-all="isExpand"
      :height="showStdList ? 'calc((100% - 70px) * 0.5)' : 'calc(100% - 50px)'"
      style="min-height: 200px"
      @current-change="handleCurrentChange"
    >
      <el-table-column label="巡更类型名称" prop="patTypeName" show-overflow-tooltip min-width="200" />
      <el-table-column label="检查要求" prop="checkRequire" show-overflow-tooltip min-width="200" />
      <el-table-column label="是否启用" align="center" min-width="80">
        <el-tag slot-scope="{ row }" size="small" :type="row.isEnable ? 'primary' : 'info'">{{ row.isEnable ? '启用' : '禁用' }}</el-tag>
      </el-table-column>
      <el-table-column label="排序" prop="seq" align="center" width="50" />
      <el-table-column label="操作" align="center" width="180">
        <div slot-scope="{ row }" @click.stop>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="$refs.EditItem.open(row, { treeData: list })" v-if="showBtns.edit">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" :loading="row.removeLoading" @click="handleDelete(row)" v-if="showBtns.remove">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="$refs.EditItem.open({ parentId: row.patTypeId }, { treeData: list })" v-if="showBtns.add">新增</el-button>
        </div>
      </el-table-column>
    </el-table>

    <StdList ref="StdList" />
    <EditItem ref="EditItem" v-model="showEditItem" @ok="getList" />
  </div>
</template>
<script>
// 巡更类型列表
import auth from '@/plugins/auth'
import { debounce, flatList2tree, isLikeOrEqual } from '@/utils'
import { listPatType, delPatType } from '@/api/cq/patrol'
import EditItem from './components/EditPatType'
import StdList from './components/PatStandardList'
export default {
  name: 'PatTypeList',
  components: { EditItem, StdList },
  data() {
    return {
      isExpand: true,
      listLoading: false,
      list: [],
      filteredList: [],
      queryParams: {
        patTypeName: ''
      },
      showEditItem: false,
      showStdList: false // 显示检查标准列表
    }
  },
  computed: {
    disableAction() {
      return this.listLoading
    },
    showBtns() {
      // 操作按钮权限
      const permCode = 'cq:patrol:type'
      const edit = auth.hasPermi(`${permCode}:edit`)
      const add = auth.hasPermi(`${permCode}:add`)
      const remove = auth.hasPermi(`${permCode}:remove`)
      const enable = auth.hasPermi(`${permCode}:enable`)
      const disable = auth.hasPermi(`${permCode}:disable`)
      return { edit, add, remove, enable, disable }
    }
  },
  watch: {
    queryParams: {
      deep: true,
      handler() {
        this.handleQueryDebounce()
      }
    }
  },
  created() {
    this.handleQueryDebounce = debounce(this.handleQuery)
    this.handleExpandDebounce = debounce(this.handleExpand)
    this.getList()
  },
  methods: {
    // 递归切换展开状态
    setChildren(children, expanded) {
      children.map(row => {
        this.$refs.table.toggleRowExpansion(row, expanded)
        if (row.children) this.setChildren(row.children, expanded)
      })
    },
    // 展开/折叠
    handleExpand() {
      this.isExpand = !this.isExpand
      this.setChildren(this.filteredList, this.isExpand)
    },
    async getList() {
      this.handleCurrentChange()
      this.listLoading = true
      const res = await listPatType().catch(() => false)
      this.listLoading = false
      if (res === false) return

      let data = res.data || []
      data.map(i => {
        i.removeLoading = false
      })
      data = flatList2tree(data, { id: 'patTypeId' })
      this.list = data
      this.handleQuery()
    },
    handleQuery() {
      // 本地树形搜索
      const { patTypeName } = this.queryParams
      const opts = { like: { patTypeName } }
      const list = JSON.parse(JSON.stringify(this.list))
      const recursion = list =>
        list.filter(item => {
          if (item.children?.length) item.children = recursion(item.children)
          return isLikeOrEqual(item, opts) || item.children?.length
        })
      const data = recursion(list)
      this.filteredList = data
      this.isExpand = true
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.getList()
    },
    async handleDelete(item) {
      if (item.removeLoading) return
      const res1 = await this.$confirm(`确认删除：${item.patTypeName}？`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      item.removeLoading = true
      const res = await delPatType(item.patTypeId).catch(() => false)
      item.removeLoading = false
      if (res === false) return

      this.msgSuccess('删除成功')
      this.getList()
    },
    handleCurrentChange(item) {
      const show = !!item?.patTypeId
      this.showStdList = show
      show ? this.$refs.StdList?.open({ patTypeId: item.patTypeId }) : this.$refs.StdList?.reset()
    }
  }
}
</script>
<style lang="scss" scoped>
.table::before {
  content: none;
}
</style>
